/*
 Copyright 2007 Razvan Taranu

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
package generators;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import com.thoughtworks.qdox.model.JavaParameter;
import com.thoughtworks.qdox.model.JavaSource;
import com.thoughtworks.qdox.model.Type;

public class JavaProxies {
    private final Log log = LogFactory.getLog(JavaProxies.class);
    
    private static final String proxyTemplate;
    static {
        proxyTemplate = Utils.readRessource("templates/java/proxies/ProxyTemplate.tpl");
    }

    private static final String methodTemplate;
    static {
        methodTemplate = Utils.readRessource("templates/java/proxies/MethodTemplate.tpl");
    }

    private String beansPackage;

    private String jsonizersPackage;
    private String proxiesPackage;

    public void run() {
        log.info("generating JAVA proxies");

        for (JavaSource source : JavaHelper.getRemoteServiceSources()) {
            log.info("processing " + source.getURL());

            JavaClass javaClass = source.getClasses()[0];
            String content = generate(javaClass);

            JavaHelper.writeProxy(javaClass.getName(), content);
        }

        JavaHelper.copyProxies();
    }

    public String generate(JavaClass javaClass) {
        // @@proxiesPackage@@
        // @@jsonizersPackage@@
        // @@serviceName@@

        String output = proxyTemplate;

        output = output.replaceAll("@@proxiesPackage@@", proxiesPackage);
        output = output.replaceAll("@@jsonizersPackage@@", jsonizersPackage);
        output = output.replaceAll("@@beansPackage@@", beansPackage);
        output = output.replaceAll("@@serviceName@@", javaClass.getName());

        List<String> proxyMethods = new ArrayList<String>();
        for (JavaMethod javaMethod : javaClass.getMethods()) {
            log.debug("javaMethod = " + javaMethod.getName());

            String proxyMethod = generateMethod(javaMethod);
            proxyMethods.add(proxyMethod);
        }

        String join = StringUtils.join(proxyMethods, "\n");
        output = output.replaceAll("@@proxyMethods@@", join);

        return output;
    }

    public String generateMethod(JavaMethod javaMethod) {
        String output = methodTemplate;

        output = output.replaceAll("@@methodName@@", javaMethod.getName());

        List<String> methodParams = new ArrayList<String>();
        
        JavaParameter[] parameters = javaMethod.getParameters();
        for (JavaParameter parameter : parameters) {

            String paramType = parameter.getType().getGenericValue();
            String paramName = parameter.getName();

            String methodParam = paramType;
            methodParam += (parameter.getType().isArray()) ? "[]" : "";
            methodParam += " " + paramName;

            methodParams.add(methodParam);
        }
        methodParams.add("final AsyncCallback<@@methodReturnType@@> callback");
        
        Type returns = javaMethod.getReturns();
        String methodReturnType;
        if (returns.getValue().equals("void")) {
            methodReturnType = "Void"; // java.lang.Void
            
        } else {
            methodReturnType = returns.getGenericValue();
            methodReturnType += (returns.isArray()) ? "[]" : "";
        }
        
        output = output.replaceAll("@@methodParams@@", StringUtils.join(methodParams, ", "));
        output = output.replaceAll("@@methodReturnType@@", methodReturnType);

        List<String> paramsToJson = paramsToJson(parameters);

        output = output.replaceAll("@@paramsToJson@@", StringUtils.join(paramsToJson, "\n        "));

        if (returns.getValue().equals("void")) {
            output = output.replaceAll("@@resultToJava@@", "(Void) GWT.create(Void.class)");
        } else {
            String resultToJava = resultToJava(returns);

            output = output.replaceAll("@@resultToJava@@", resultToJava);
        }

        return output;
    }

    public List<String> paramsToJson(JavaParameter[] parameters) {
        List<String> paramList = new ArrayList<String>();

        for (int i = 0, n = parameters.length; i < n; i++) {
            JavaParameter param = parameters[i];

            String value = param.getName();
            Type type = param.getType();

            String paramToJson = "argv.set(@@index@@, @@toJson@@);";

            String index = "" + i;
            String toJson = JavaHelper.valueToJson(value, type);

            paramToJson = paramToJson.replace("@@index@@", index);
            paramToJson = paramToJson.replace("@@toJson@@", toJson);

            paramList.add(paramToJson);
        }

        return paramList;
    }

    public String resultToJava(Type type) {
        return JavaHelper.valueToJava("value", type);
    }

    public void setBeansPackage(String beansPackage) {
        this.beansPackage = beansPackage;
    }

    public void setJsonizersPackage(String jsonizersPackage) {
        this.jsonizersPackage = jsonizersPackage;
    }

    public void setProxiesPackage(String proxiesPackage) {
        this.proxiesPackage = proxiesPackage;
    }
}
